package com.imc.platform.base.lesson.controller;

import com.imc.api.order.pojo.Lesson;
import com.imc.api.order.pojo.LessonAtt;
import com.imc.api.order.pojo.LessonSchedule;
import com.imc.core.utils.ClearTempImg;
import com.imc.core.utils.MenuUtils;
import com.imc.core.utils.UploadUtiles;
import com.imc.platform.base.lesson.pojo.LessonOrgCat;
import com.imc.platform.base.lesson.service.LessonService;
import com.imc.platform.base.user.pojo.User;
import com.imc.platform.base.user.pojo.UserDesc;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tanweiping on 2018/10/10.
 */
/*
* 类描述：后端课程控制器
* 开发者：tanweiping
* 创建日期：2018/10/10 14:16
*/
@Slf4j
@RequestMapping("/lesson")
@Controller
public class BackLessonController {

    public static final String imgUrl = "/images/lesson/";

    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;

    @Autowired
    LessonService lessonService;

    @Autowired
    MenuUtils menuUtils;
    @Autowired
    UploadUtiles uploadUtiles;
    @Autowired
    ClearTempImg clearTempImg;

    /*
    * tanweiping  2018/10/10 14:15
    * 方法描述：课程主页
    */
    @GetMapping("/showLesson")
    String lesson(HttpServletRequest request, Model model,String menuId){
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request,menuId));
        model.addAttribute("menuId",menuId);
        return "base/lesson/lesson";
    }

    /*
     * tanweiping  2018/10/10 14:15
     * 方法描述：课程主页
     */
    @GetMapping("/showVoide")
    String voide(HttpServletRequest request, Model model,String menuId){
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request,menuId));
        model.addAttribute("menuId",menuId);
        return "base/lesson/voide";
    }

    /*
     * tanweiping  2018/10/10 14:15
     * 方法描述：课程主页
     */
    @GetMapping("/showMeal")
    String meal(HttpServletRequest request, Model model,String menuId){
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request,menuId));
        model.addAttribute("menuId",menuId);
        return "base/lesson/meal";
    }

    @GetMapping("/updatePage")
    String updatePage(@RequestParam String lessonType,@RequestParam String lessonId,@RequestParam String menuId,Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","update");
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        return "base/lesson/updateLesson";
    }

    @GetMapping("/updateVoidePage")
    String updateVoidePage(@RequestParam String lessonType,@RequestParam String lessonId,@RequestParam String menuId,Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","update");
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        return "base/lesson/updateLesson";
    }

    @GetMapping("/updateMealPage")
    String updateMealPage(@RequestParam String lessonType,@RequestParam String lessonId,@RequestParam String menuId,Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","update");
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        return "base/lesson/updateLesson";
    }

    @GetMapping("/showAddLessonPage")
    String showAddLessonPage(@RequestParam String lessonType,@RequestParam String menuId,Model model){
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","add");
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        return "base/lesson/addLesson";
    }

    @GetMapping("/showAddVoidePage")
    String showAddVoidePage(@RequestParam String lessonType,@RequestParam String menuId,Model model){
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","add");
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        return "base/lesson/addLesson";
    }

    @GetMapping("/showAddMealPage")
    String showAddMealPage(@RequestParam String lessonType,@RequestParam String menuId,Model model){
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","add");
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        return "base/lesson/addLesson";
    }

    @RequestMapping(value = "/showAddLessonTeacher",method = RequestMethod.GET)
    String showAddLessonTeacher(){
        return "base/common/getTableObject";
    }

    @GetMapping("/showLessonPage")
    String showLessonPage(@RequestParam String lessonId,@RequestParam String lessonType,Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","show");
        return "base/lesson/showLesson";
    }
    @GetMapping("/showVoidePage")
    String showVoidePage(@RequestParam String lessonId,@RequestParam String lessonType,Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","show");
        return "base/lesson/showLesson";
    }
    @GetMapping("/showMealPage")
    String showMealPage(@RequestParam String lessonId,@RequestParam String lessonType,Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        model.addAttribute("queryType","show");
        return "base/lesson/showLesson";
    }

    @GetMapping("/showAddLessonSchedule")
    String showAddLessonSchedule(@RequestParam String lessonId,@RequestParam String lessonType, Model model){
        model.addAttribute("lessonId",lessonId);
        model.addAttribute("lessonType",lessonType);
        return "base/lesson/addLessonSchedule";
    }
    @GetMapping("/showUpdateSchedule")
    String showUpdateSchedule(@RequestParam String scheduleId,@RequestParam String lessonType, Model model){
        model.addAttribute("scheduleId",scheduleId);
        model.addAttribute("lessonType",lessonType);
        return "base/lesson/updateSchedule";
    }
    @GetMapping("/showScheduleDet")
    String showScheduleDet(@RequestParam String scheduleId,@RequestParam String lessonType, Model model){
        model.addAttribute("scheduleId",scheduleId);
        model.addAttribute("lessonType",lessonType);
        return "base/lesson/showSchedule";
    }
    @GetMapping("/showLessonChartPage")
    String showLessonChartPage(@RequestParam String lessonId, Model model){
        model.addAttribute("lessonId",lessonId);
        return "base/lesson/showLessonChart";
    }

    @GetMapping("/queryLessonChartList")
    @ResponseBody
    ResultDTO queryLessonChartList(String parm,Pageable pageable,HttpServletRequest request){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    User user=(User) request.getSession().getAttribute("currentUser");
                    Map<String,Object>parmMap=new HashMap<>();
                    parmMap.put("lessonId",parm);
                    parmMap.put("select","");
                    if(user.getRoleId().equals("3")){
                           parmMap.put("orgId",user.getOrgId());
                    }else if(user.getRoleId().equals("1") || user.getRoleId().equals("2")){

                    }else {
                        t.setIsSuccess(false);
                        t.setMessage("该角色无权限查看统计详情");
                    }
                    val pageInfo = lessonService.queryLessonChartList(parmMap,pageable);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                    t.setIsSuccess(true);
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询主要列表展示失败");
                }
        );
    }

    @GetMapping("/queryListByParm")
    @ResponseBody
    ResultDTO queryListByParm(@RequestParam String select,@RequestParam String lessonId, Pageable pageable,HttpServletRequest request){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    User user=(User) request.getSession().getAttribute("currentUser");
                    Map<String,Object>parmMap=new HashMap<>();
                    parmMap.put("lessonId",lessonId);
                    parmMap.put("select",select);
                    if(user.getRoleId().equals("3")){
                        parmMap.put("orgId",user.getOrgId());
                    }else if(user.getRoleId().equals("1") || user.getRoleId().equals("2")){

                    }else {
                        t.setIsSuccess(false);
                        t.setMessage("该角色无权限查看统计详情");
                    }
                    val pageInfo = lessonService.queryLessonChartList(parmMap,pageable);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                    t.setIsSuccess(true);
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询主要列表展示失败");
                }
        );
    }

    @GetMapping("/queryScheduleList")
    @ResponseBody
    ResultDTO queryScheduleList(String parm,Pageable pageable){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    val pageInfo = lessonService.queryScheduleList(parm,pageable);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                    t.setIsSuccess(true);
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询主要列表展示失败");
                }
        );
    }

    @GetMapping("/queryTeacherList")
    @ResponseBody
    ResultDTO queryTeacherList(Pageable pageable){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    val pageInfo = lessonService.queryTeacherList(pageable);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询主要列表展示失败");
                }
        );
    }

    @GetMapping("/queryListBySearch")
    @ResponseBody
    ResultDTO queryListBySelect(String search,Pageable pageable){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    val pageInfo = lessonService.queryListBySelect(search,pageable);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询主要列表展示失败");
                }
        );
    }

    @GetMapping("/queryScheduleDetByScheduleId")
    @ResponseBody
    ResultDTO queryScheduleDetByScheduleId(String scheduleId){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    t.setData(lessonService.queryScheduleDetByScheduleId(scheduleId));
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询课时详情失败");
                }
        );
    }
    /*
    * tanweiping  2018/10/10 14:28
    * 方法描述：主要列表展示
    */
    @GetMapping("/queryList")
    @ResponseBody
    ResultDTO queryList(HttpServletRequest request,String parm, Pageable pageable){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    User user=(User) request.getSession().getAttribute("currentUser");
                    val pageInfo = lessonService.queryList(user.getRoleId(),user.getOrgId(),parm,pageable);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询主要列表展示失败");
                }
        );
    }

    @GetMapping("queryCatAll")
    @ResponseBody
    ResultDTO queryCatAll(String catType){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    t.setData(lessonService.queryCatAll(catType));
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查询所有类型失败");
                }
        );
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class LessonTuple{
        private Lesson lesson;
        private LessonSchedule lessonSchedule;
        private List<LessonOrgCat> lessonOrgCats;
    }

   /*
   * tanweiping  2018/10/10 14:23
   * 方法描述：创建课程
   */
   @PostMapping("/addLesson")
   @ResponseBody
   ResultDTO addLesson(@RequestBody LessonTuple lessonTuple,HttpServletRequest request){
       return iComboExecptionForTFunc.executeFlow(
               ResultDTO.builder().build(),
               t->{
                   HttpSession session = request.getSession();
                   User user=(User) session.getAttribute("currentUser");
                   if(user.getOrgId().equals("")){
                       t.setIsSuccess(false);
                       t.setMessage("操作用户无组织结构，请联系管理员");
                       t.setCode("201");
                   }else {
                       Lesson lesson=lessonTuple.getLesson();
                       lesson.setOrgId(Integer.parseInt(user.getOrgId()));
                       lesson.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                       lessonService.addLesson(lesson);
                       t.setData(lesson.getId());
                       t.setMessage("创建成功");
                   }
               },
               (e,t)->{
                   e.printStackTrace();
                   t.setIsSuccess(false);
                   t.setMessage("课程添加失败");
               }
       );
   }

   @PostMapping("/addSchedule")
   @ResponseBody
   ResultDTO addSchedule(@RequestBody LessonTuple lessonTuple){
       return iComboExecptionForTFunc.executeFlow(
               ResultDTO.builder().build(),
               t->{
                   LessonSchedule lessonSchedule=lessonTuple.getLessonSchedule();
                   lessonSchedule.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                   lessonService.addSchedule(lessonSchedule);
               },
               (e,t)->{
                   e.printStackTrace();
                   t.setIsSuccess(false);
                   t.setMessage("课程添加失败");
               }
       );
   }
    /*
    * tanweiping  2018/10/10 14:16
    * 方法描述：课程删除，需要1个主表，3张子表的关系及记录解除
    */
    @PostMapping("/deleteById")
    @ResponseBody
    ResultDTO deleteLesson(String id){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    lessonService.deleteLessonById(id);
                    t.setData("1");
                },
                (e,t)->{
                    e.printStackTrace();

                    t.setIsSuccess(false);
                    t.setMessage("课程下架失败");
                }
        );
    }

    @PostMapping("/deleteVoideById")
    @ResponseBody
    ResultDTO deleteVoide(String id){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    lessonService.deleteLessonById(id);
                    t.setData("1");
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("课程下架失败");
                }
        );
    }

    @PostMapping("/deleteMealById")
    @ResponseBody
    ResultDTO deleteMeal(String id){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    lessonService.deleteLessonById(id);
                    t.setData("1");
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("课程下架失败");
                }
        );
    }

    @GetMapping("/queryLessonDetByLessonId")
    @ResponseBody
    ResultDTO queryLessonDetByLessonId(String lessonId){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    t.setData(lessonService.queryLessonDetByLessonId(lessonId));
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("课程查询失败");
                }
        );
    }

    @PostMapping("/delScheduleById")
    @ResponseBody
    ResultDTO delScheduleById(String id){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    lessonService.delScheduleById(id);
                    t.setData("1");
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("课时删除失败");
                }
        );
    }

//    /*
//    * tanweiping  2018/10/10 14:16
//    * 方法描述：课程删除，需要1个主表，3张子表的关系及记录解除
//    */
//    @DeleteMapping("")
//    @ResponseBody
//    ResultDTO batchDeleteLesson(Principal principal,@RequestBody List<String> ids){
//        return iComboExecptionForTFunc.executeFlow(
//                ResultDTO.builder().build(),
//                t->{
//                    lessonService.deleteLesson(principal,ids);
//                },
//                (e,t)->{
//                    e.printStackTrace();
//                    log.info(e.getMessage());
//                    t.setIsSuccess(false);
//                    t.setMessage("课程删除失败");
//                }
//        );
//    }
    
    /*
    * tanweiping  2018/10/10 14:21
    * 方法描述：更新课程
    */
    @ResponseBody
    @PostMapping("/updateLesson")
    ResultDTO updateLesson(@RequestBody LessonTuple lessonTuple){
        ResultDTO resultDTO=new ResultDTO();
        lessonService.updateLesson(lessonTuple.getLesson());
        return ResultDTO.builder().data(lessonTuple.getLesson().getId()).build();
    }

    @PostMapping("/updayeSchedule")
    @ResponseBody
    ResultDTO updateSchedule(@RequestBody LessonTuple lessonTuple){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    lessonService.updateSchedule(lessonTuple.getLessonSchedule());
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("课程删除失败");
                }
        );
    }

    @PostMapping("/addLessonAtt")
    @ResponseBody
    ResultDTO addLessonAtt(@RequestParam("file") MultipartFile file, @RequestParam("id") String id){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    if(StringUtils.isNotEmpty(id)){
                        //入库路径
                        String realPath = uploadUtiles.getCurrentAddress(imgUrl);
                        //上传路径
                        String savePath = uploadUtiles.getLocationAddress(imgUrl);
                        String fileName = uploadUtiles.getUpImg(savePath, file);
                        if (null != fileName && !"".equals(fileName)) {
                            LessonAtt lessonAtt = LessonAtt.builder()
                                    .attachmentType("1")
                                    .attachmentName(fileName)
                                    .attachmentUrl(realPath+fileName)
                                    .createTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                                    .lessonId(Integer.parseInt(id))
                                    .build();
                            lessonService.addLessonAtt(lessonAtt);
                            t.setIsSuccess(true);
                            t.setData(lessonAtt.getAttachmentUrl());
                        } else {
                            t.setIsSuccess(false);
                            t.setMessage("图片上传失败");
                        }
                    }else {
                        t.setIsSuccess(false);
                        t.setMessage("请完成基本信息的添加");
                    }

                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("新增教师风采失败");
                }
        );
    }

    @PostMapping("/delLessonAtt")
    @ResponseBody
    public ResultDTO delUserDesc(@RequestParam("id") String id, @RequestParam("imgUrl") String imgUrl) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    clearTempImg.clearImgs(imgUrl);
                    lessonService.delLessonAtt(id,imgUrl);
                    t.setIsSuccess(true);
                    t.setMessage("课程图片删除成功");
                }, (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("删除失败");
                }
        );
    }

}
